import $API from '@/api/services'
import { isWxBrowser } from '@/utils'
import AUTH from '@/utils/auth'
const getToken = () => AUTH.getToken()

const user = {
  state: {
    userInfo: null,
    addressList: null,
    userBalance: null,
    orderData: null,
    userWelfare: null, // 用户抢到的红包
    welfareCache: {},
    welfareHistory: null,
    logined: false
  },
  actions: {
    // 拉取用户信息
    getUserInfo({ commit }) {
      $API('getUserInfoAsync', []).then(res => {
        // console.log(res)
        if (res && res.code == 100) {
          commit('SAVE_USER_INFO', res.data)
        }
      })
    },
    userLogin({ commit }, options) {
      $API('login', [options]).then(res => {
        if (res && res.data) {

          // 写入cookie
          let userCookieStr = ''
          for(var k in res.data) {
            userCookieStr += k + '=' + encodeURIComponent(res.data[k]) + '&'
          }
          userCookieStr = userCookieStr.slice(0, -1)
          AUTH.setToken(userCookieStr)

          // 845定制
          if ($globalconfig.MODULES.IS_LANJIUKJ_PROGRAM_OPEN) {
            window.history.go(0)
            return
          }

          // 刷新场景数据
          this.dispatch('fetchSceneData', this.getters.panoId)

          // 拉取购物车数据
          this.dispatch('getUserInfo')
          this.dispatch('fetchCartGoods')

          // 收藏状态
          this.dispatch('getCollectStatus', res.data.access_token)

          $VM.$vgo.tip('登陆成功！', 'success')
        }
      })
    },
    // 地址
    fetchUserAddress({ commit }) {
      $API('getAddress', []).then(res => {
        if (res.data) {
          commit('SAVE_USER_ADDRESS', res.data)
        }
      })
    },
    // 添加或更新地址
    addOrUpdateAddress({ commit }, opts) {
      $API('addOrUpdateAddress',[opts]).then(res => {
        if(res) {
          this.dispatch('fetchUserAddress')
        }
      })
    },
    // 删除地址
    delAddress({ commit }, addressId) {
      $API('deleteAddress',[addressId]).then(res => {
        if(res) {
          $VM.$vgo.tip('删除成功', 'success')
          commit('DELETE_ADDRESS', addressId)
        }
      })
    },
    // 获取余额
    getUserBalance({ commit }, money) {
      $API('getBalance', [$VM.$route.params.panoId]).then(res => {
        if(res.data) {
          commit('SAVE_USER_BALANCE', res.data.bank)
        }
      })
    },
    // 创建订单
    createOrder({ commit }, obj) {
      $API('createProductOrder', [obj.cartIds, obj.address]).then(res => {
        if(res.data) {
          const options = {
            pano_id: this.getters.panoId,
            ordertype: 4,
            productid: res.data,
            paytype: obj.payment,
            totalfee: obj.money,
            return_url: obj.url,
            iswx: obj.iswx,
            cartids: obj.cartIds
          }
          this.dispatch('goodsPay', options)
        }
      }).catch(() => {
        $VM.$vgo.emit('createorder:failed')
      })
    },
    // 商品付款
    goodsPay({ commit }, opts) {
      $API('payOrder', [opts]).then(res => {
        if(res) {
          if(!!res.data) {
            let payUrl
            const openid = (this.getters && this.getters.userInfo) ? this.getters.userInfo.wx_openid : ''
            if(isWxBrowser()) {
              payUrl = res.data + '&iswx=true&pano_id='+ this.getters.panoId + '&openid=' + openid
            } else {
              payUrl = res.data + '&pano_id='+ this.getters.panoId +'&openid=' + openid
            }
            window.location.href = payUrl
          } else {
            $VM.$vgo.emit('pay:success', {data: res.data})
            this.dispatch('updateCartGoods', opts.cartids)
          }
        }
      }).catch(() => {
        $VM.$vgo.emit('pay:failed')
      })
    },
    // 获取用户订单
    fetchUserOrder({ commit }, pageIndex = 1, pageSize = 10) {
      $API('getProductOrderList', [pageIndex, pageSize]).then(res => {
        if(res.data) {
          commit('SAVE_USER_ORDER', res.data)
        }
      })
    },
    // 获取红包信息
    fetchUserWelfare({ commit, state }, pageIndex, pageSize) {
      $API('grablistWelfare', [pageIndex, pageSize]).then(res => {
        if(res.data) {
          commit('SAVE_USER_WELFARE', res.data)
        }
      })
    },
    // 抢红包
    grabWelfare({ commit }, obj) {
      const { id, phone } = obj
      $API('grabWelfare',[id, phone]).then(res => {
        if(res && res.data) {
          $API('getWelfare',[id]).then(r => {
            r.data.totalmoney = res.data
            $VM.$vgo.emit('modal:welfale', r.data)
          })
        } else {
          $VM.$vgo.tip(res.msg, 'error')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取用户抢到的红包信息
    fetchWelfareHistory({ commit }, ary) {
      $API('grablistWelfare', ary).then(res => {
        if(res.data) {
          commit('SAVE_WELFARE_HISTORY', res.data)
        }
      })
    },
    payReward({commit}, options) {
      // console.log(window.navigator.userAgent.toLowerCase().indexOf('miniprogram'));
      // console.log(window.navigator.userAgent.toLowerCase().indexOf('miniprogram') != -1 && options.paytype == '2');

      if (window.navigator.userAgent.toLowerCase().indexOf('miniprogram') != -1 && options.paytype == '2') { //判断是否小程序打开 且 微信支付
        let str = '/pages/webview-pay/index?paytype=' + options.paytype + '&productid=' + options.productid + '&totalfee=' + options.totalfee + '&token=' + getToken() + '&return_url=' + $globalconfig.URLS.API + '#' + options.return_url
        // console.log(wx)
        wx.miniProgram.navigateTo({
          url:  str,
          fail: res => {
            console.log(res)
          },
        })
        $VM.$router.go(-1)
      } else {
        $API('payOrder', [options]).then(res => {
          if(res && res.data) {
            const openid = (this.getters && this.getters.userInfo) ? this.getters.userInfo.wx_openid : ''
            // 跳转到微信或者支付宝支付
            window.location.href = res.data + '&pano_id='+ options.productid +'&openid=' + openid
          } else {
            if(res.code == 100){
              $VM.$vgo.tip('打赏成功', 'success')
              $VM.$vgo.emit('payreward:success')
            }
          }
        })
      }
    }
  },
  mutations: {
    SAVE_USER_INFO: (state, data) => {
      state.userInfo = data
      state.logined = true
    },
    SAVE_USER_ADDRESS: (state, data) => {
      state.addressList = data
    },
    SAVE_USER_BALANCE: (state, balance) => {
      state.userBalance = balance
    },
    DELETE_ADDRESS: (state, addressId) => {
      state.addressList.map((item, idx) => {
        if(item.addressid == addressId) {
          state.addressList.splice(idx, 1)
        }
      })
    },
    SAVE_USER_ORDER: (state, orderData) => {
      state.orderData = orderData
    },
    SAVE_USER_WELFARE: (state, data) => {
      state.userWelfare = data
    },
    SAVE_WELFARE_HISTORY: (state, data) => {
      state.welfareHistory = data
    }
  }
}

export default user
